﻿using System;
using System.Globalization;
using Pantry.Business;
using Pantry.Entity;
using System.Web.UI;
using Pantry.Commons;


namespace Pantry.Web.Users
{
    public partial class TeamDetail : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            PrepareDelegates();
            if (IsPostBack) return;
            var strDepartmentId = Request.QueryString.Get("DepartmentId");
            if (!Validates.IsNaturalNumber(strDepartmentId))
            {
                Response.Redirect(UrlBackHistory());
            }

            BindToDropDownListNation();
            var teamBus = new TeamBus();
            var teamId = Convert.ToInt32(Request.QueryString.Get("Id"),CultureInfo.InvariantCulture);
            var team = (Team)teamBus.RetrieveEntity(teamId);
            ButtonDeactivate.Enabled = false;
            if (team != null)
            {
                BindTeamToWeb(team);
                if (!team.IsActive)
                {
                    teamBus.ChangeIsActive("Team","IsActive","True","TeamId",team.TeamId);
                }
                LabelTitle.Text = "Update Team";
                ButtonSave.Text = "Save";
                ButtonDeactivate.Enabled = true;
            }
            else
            {
                InitDataToWeb(strDepartmentId);
                BindDefaultValueForTypeOfBusiness(Convert.ToInt32(strDepartmentId,CultureInfo.InvariantCulture));
                LabelTitle.Text = "Create Team";
                ButtonSave.Text = "Insert";
                ButtonDeactivate.Visible = false;
            }
        }

        protected void ButtonBackOnClicked(object sender, EventArgs e)
        {
            Response.Redirect(UrlBackHistory());
        }
            
        protected void RadioButtonCopyAddressSelectedIndexChanged(object sender, EventArgs e)
        {
            if (RadioButtonCopyAddress.SelectedValue == "1")
            {
                var organizationBus = new OrganizationBus();
                var organizationId = Convert.ToInt32(HiddenFieldOrganizationId.Value, CultureInfo.InvariantCulture);
                var organization = organizationBus.ReturnOrganizationById(organizationId);
                TextBoxAddress1.Text = organization.Address1;
                TextBoxAddress2.Text = organization.Address2;
                TextBoxAddress3.Text = organization.Address3;
            }

            if (RadioButtonCopyAddress.SelectedValue == "2")
            {
                var deparmentBus = new DepartmentBus();
                var deparmentId = Convert.ToInt32(HiddenFieldDepartmentId.Value, CultureInfo.InvariantCulture);
                var table = deparmentBus.GetDepartmentById(deparmentId);
                var row = table.Rows[0];
                TextBoxAddress1.Text = row[6].ToString();
                TextBoxAddress2.Text = row[7].ToString();
                TextBoxAddress3.Text = row[8].ToString();
            }
        }

        public void ButtonSaveOnClicked(Object sender,EventArgs eventArgs)
        {
            var team = CreateTeam();
            if (team==null)
            {
                return;
            }

            if (team.TeamId!=-1)
            {
                UpdateTeam(team);
            }
            else
            {
                InsertTeam(team);
            }
        }

        public void ButtonActiveClicked(object sender,EventArgs eventArgs)
        {
            var teamBus = new TeamBus();
            var teamId = Convert.ToInt32(HiddenFieldTeamId.Value, CultureInfo.InvariantCulture);
            teamBus.ChangeIsActive("Team", "IsActive", "False", "TeamId", teamId);
            Response.Redirect(UrlBackHistory());
        }

        private void PrepareDelegates()
        {
            ListContact.SendContactToPage += delegate(string contact)
            {
                var contacts = contact.Split('$');
                HiddenFieldContactId.Value = contacts[0];
                TextBoxContactName.Text = contacts[1];
            };

            ListTypeOfBusiness.SendvaluesToThePage += delegate(string typeOfBusiness)
            {
                var listType = typeOfBusiness.Split('$');
                TextBoxTypeName.Text = listType[0];
                TextBoxSicCode.Text = listType[1];
                HiddenFieldTypeOfBusinessId.Value = listType[2];
            };

            ListPostcode.sendPostcodeToPage += delegate(string postcode)
            {
                var listPostcode = postcode.Split('$');
                TextBoxPostcode.Text = listPostcode[0].Trim();
                TextBoxTownVillageCity.Text = listPostcode[1];
                TextBoxCounty.Text = listPostcode[2];

            };
        }

        private void BindTeamToWeb(Team team)
        {
            HiddenFieldTeamId.Value = team.TeamId.ToString(CultureInfo.InvariantCulture);
            HiddenFieldDepartmentId.Value = team.DepartmentId.ToString(CultureInfo.InvariantCulture);
            HiddenFieldOrganizationId.Value = team.OrganizationId.ToString(CultureInfo.InvariantCulture);
            HiddenFieldIsActive.Value = team.IsActive.ToString(CultureInfo.InvariantCulture);
            HiddenFieldContactId.Value = team.ContactId.ToString(CultureInfo.InvariantCulture);
            HiddenFieldTypeOfBusinessId.Value = team.TypeOfBusinessId.ToString(CultureInfo.InvariantCulture);

            TextBoxTeamName.Text = team.TeamName;
            TextBoxTypeName.Text = team.TypeName;
            TextBoxShortDescription.Text = team.ShortDescription;
            TextBoxSicCode.Text = team.SicCode;
            TextBoxContactName.Text = team.ContactName;
            TextBoxFullDescription.Text = team.FullDescription;
            TextBoxAddress1.Text = team.AddressLine1;
            TextBoxPhone.Text = team.Phone;
            TextBoxAddress2.Text = team.AddressLine2;
            TextBoxFax.Text = team.Fax;
            TextBoxAddress3.Text = team.AddressLine3;
            TextBoxEmail.Text = team.Email;
            TextBoxPostcode.Text = team.Postcode;
            TextBoxWebAddress.Text = team.WebAddress;
            TextBoxTownVillageCity.Text = team.Town;
            TextBoxCounty.Text = team.County;
            DropDownListCountry.SelectedValue = team.CountryId.ToString(CultureInfo.InvariantCulture);
        }

        private void BindDefaultValueForTypeOfBusiness(int departmentId)
        {
            var organizationBus = new OrganizationBus();
            var organization = organizationBus.RetrieveOrganizationIdByDepartment(departmentId);
            HiddenFieldTypeOfBusinessId.Value = organization.TypeOfBusinessId.ToString(CultureInfo.InvariantCulture);
            TextBoxWebAddress.Text = organization.WebAddress;
            var teamBus = new TeamBus();
            var typeOfBusinessSearch = teamBus.RetrieveTypeOfBusinessByDepartment(organization.TypeOfBusinessId);
            TextBoxTypeName.Text = typeOfBusinessSearch.TypeName;
            TextBoxSicCode.Text = typeOfBusinessSearch.SicCode;
        }

        private void InitDataToWeb(string strDepartmentId)
        {
            var departmentId = Convert.ToInt32(strDepartmentId,CultureInfo.InvariantCulture);
            HiddenFieldDepartmentId.Value = departmentId.ToString(CultureInfo.InvariantCulture);
            var organizationId = new OrganizationBus().RetrieveOrganizationIdByDepartment(departmentId).Id;
            HiddenFieldOrganizationId.Value = organizationId.ToString(CultureInfo.InvariantCulture);
        }

        private Team CreateTeam()
        {
            if (String.IsNullOrEmpty(TextBoxTeamName.Text))
            {
                TextBoxTeamName.Focus();
                // Notify name's empty
                const string script = @"showmessage('Name of Team is empty !','ERROR','','false');";
                ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "resetDefaultFired", script, true);
                return null;
            }

            // Verify postcode
            var postcode = TextBoxPostcode.Text.Trim();
            if (!Validates.IsEmptyOrNumber(postcode))
            {
                TextBoxPostcode.Focus();
                // Notifile the postcode invalid
                const string script = @"showmessage('Postcode is invalid !','ERROR','','false');";
                ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "resetDefaultFired", script, true);
                return null;
            }
            var teamBus = new TeamBus();
            if (teamBus.CheckUnique("County", "Postcode",postcode.ToString(CultureInfo.CurrentCulture))<1)
            {
                TextBoxPostcode.Focus();
                // Notify the postcode is incorrect
                const string script = @"showmessage('Postcode is incorrect !','ERROR','','false');";
                ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "resetDefaultFired", script, true);
                return null;
            }

            var teamId = -1;
            if (!String.IsNullOrEmpty(HiddenFieldTeamId.Value))
            {
                teamId = Convert.ToInt32(HiddenFieldTeamId.Value, CultureInfo.InvariantCulture);
            }

            var team = new Team
            {
                TeamName = TextBoxTeamName.Text,
                ShortDescription = TextBoxShortDescription.Text,
                FullDescription = TextBoxFullDescription.Text,
                DepartmentId = Convert.ToInt32(HiddenFieldDepartmentId.Value, CultureInfo.InvariantCulture),
                ContactId =(Validates.IsNaturalNumber(HiddenFieldContactId.Value))? Convert.ToInt32(HiddenFieldContactId.Value, CultureInfo.InvariantCulture):-1,
                TypeOfBusinessId = (Validates.IsNaturalNumber(HiddenFieldTypeOfBusinessId.Value))? Convert.ToInt32(HiddenFieldTypeOfBusinessId.Value, CultureInfo.InvariantCulture):-1,
                AddressLine1 = TextBoxAddress1.Text,
                AddressLine2 = TextBoxAddress2.Text,
                AddressLine3 = TextBoxAddress3.Text,
                Postcode = TextBoxPostcode.Text,
                Town = TextBoxTownVillageCity.Text,
                County = TextBoxCounty.Text,
                CountryId = Convert.ToInt32(DropDownListCountry.SelectedValue, CultureInfo.InvariantCulture),
                Phone = TextBoxPhone.Text,
                Fax = TextBoxFax.Text,
                Email = TextBoxEmail.Text,
                WebAddress = TextBoxWebAddress.Text,
                IsActive = Convert.ToBoolean(HiddenFieldIsActive.Value, CultureInfo.InvariantCulture),
                Date = DateTime.Today,
                TeamId = teamId
            };

            return team;
        }

        private void InsertTeam(Team team)
        {
            var teamBus = new TeamBus();
            string script;
            var insertTeam = teamBus.Insert(team);
            if (insertTeam == 1)
            {
                // Notify update success
                script = @"showmessage('Insert is success !','SUCCESS','"+UrlBackHistory()+"','true');";
                ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "resetDefaultFired", script, true);
            }

            if (insertTeam == -1)
            {
                // Notify connection error
                script = @"showmessage('Connection occur a error!','ERROR','','false');";
                ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "resetDefaultFired", script, true);
            }

            if (insertTeam != -2) return;
            TextBoxTeamName.Focus();
            // Notify exits Name
            script = @"showmessage('Name of Team is exits !','ERROR','','false');";
            ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "resetDefaultFired", script, true);
        }

        private void UpdateTeam(Team team)
        {
            var teamBus = new TeamBus();
            string script;
            var updateTeam = teamBus.Update(team);
            if (updateTeam == 1)
            {
                // Notify update success
                script = @"showmessage('Update is success !','SUCCESS','"+UrlBackHistory()+"','true');";
                ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "resetDefaultFired", script, true);
            }

            if (updateTeam == -1)
            {
                // Notify connection error
                script = @"showmessage('Connection occur a error!','ERROR','','false');";
                ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "resetDefaultFired", script, true);
            }

            if (updateTeam != -2) return;
            TextBoxTeamName.Focus();
            // Notify exits Name
            script = @"showmessage('Name of Team is exits !','ERROR','','false');";
            ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "resetDefaultFired", script, true);
        }

        private void BindToDropDownListNation()
        { 
            var countryBus = new CountryBus();
            var dataTable = countryBus.SelectAllCountry();
            DropDownListCountry.DataSource = dataTable.DefaultView;
            DropDownListCountry.DataValueField = "CountryId";
            DropDownListCountry.DataTextField = "CountryName";
            DropDownListCountry.DataBind();
        }

        private string UrlBackHistory()
        {
            return @"DepartmentDetails.aspx?id=" + Request.QueryString["DepartmentId"] + "&action=edit#table_wTabs-2";
        }
    }
}
